<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="活动主题" prop="activityTheme">
        <el-input v-model="queryParams.activityTheme" placeholder="请输入活动主题" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="时间" prop="constructTime">
        <!-- <el-date-picker clearable v-model="queryParams.constructTime" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择时间">
        </el-date-picker> -->
        <el-date-picker v-model="dateRange" type="datetimerange" value-format="yyyy-MM-dd" range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期" @change="handleDateChange"></el-date-picker>
      </el-form-item>
      <el-form-item label="地点" prop="place">
        <el-input v-model="queryParams.place" placeholder="请输入地点" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['staff:oneStopCommunityConstruction:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['staff:oneStopCommunityConstruction:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['staff:oneStopCommunityConstruction:remove']">删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['staff:oneStopCommunityConstruction:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getUser"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="oneStopCommunityConstructionList" @selection-change="handleSelectionChange"
      :default-sort="{ prop: 'constructTime', order: 'descending' }">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="活动主题" align="center" prop="activityTheme" />
      <el-table-column label="活动概况" align="center" prop="activityProfile" />
      <el-table-column label="参与人员类型" align="center" prop="personnelType" />
      <el-table-column label="主要参加人员名单" align="center" prop="personnelList">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.personnelList || '未填写'" placement="top">
            <div class="ellipsis">
              {{ scope.row.personnelList || '未填写' }}
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="时间" align="center" prop="constructTime" width="180" sortable>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.constructTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="地点" align="center" prop="place" />
      <el-table-column label="服务学生人次" align="center" prop="stuNumber" />
      <el-table-column label="活动照片" align="center" prop="activityPhoto" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.activityPhoto" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="auditStatus">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.auditStatus === 0">待审核</el-tag>
          <el-tag type="success" v-else-if="scope.row.auditStatus === 1">通过</el-tag>
          <el-tag type="danger" v-else>不通过</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row, '查看修改意见')"
            v-if="scope.row.auditStatus == 2"
            v-hasPermi="['staff:oneStopCommunityConstruction:edit']">查看修改意见</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-if="scope.row.auditStatus == 2 && roleGroup.includes('管理员')"
            v-hasPermi="['staff:oneStopCommunityConstruction:remove']">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row, '审核')"
            v-if="scope.row.auditStatus == 0 && roleGroup.includes('管理员')"
            v-hasPermi="['staff:oneStopCommunityConstruction:edit']">审核</el-button>
          <el-button size="mini" type="text" icon="el-icon-search" @click="handleUpdate(scope.row, '查看详情')"
            v-if="scope.row.auditStatus == 0 || scope.row.auditStatus == 1">查看详情</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row, '修改')"
            v-if="scope.row.auditStatus == 2 && roleGroup.includes('管理员')"
            v-hasPermi="['staff:oneStopCommunityConstruction:edit']">修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getUser" />

    <!-- 添加或修改一站式社区模块：社区建设对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" v-if="title === '审核'">
        <el-form-item label="活动发起人" prop="eventPromoter">
          <el-input v-model="form.eventPromoter" placeholder="请输入内容" disabled />
        </el-form-item>
        <el-form-item label="审核状态" prop="auditStatus">
          <el-radio-group v-model="form.auditStatus">
            <el-radio :label="0" disabled>待审核</el-radio>
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="修改意见" prop="editOpinion" v-if="form.auditStatus === 2">
          <el-input v-model="form.editOpinion" type="textarea" rows="5" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" v-else-if="title === '查看修改意见'">
        <el-form-item label="修改意见" prop="editOpinion">
          <el-input v-model="form.editOpinion" type="textarea" rows="5" placeholder="请输入内容" disabled />
        </el-form-item>
      </el-form>
      <div v-else-if="title === '查看详情'">
        <div style="text-align: center; font-size: 20px; font-weight: bold; margin-bottom: 20px;">{{ form.activityTheme
          }}活动
        </div>
        <div>
          <div style="margin-left: 20px;">
            <div style="display: flex; justify-content: space-around;">
              <div style="margin-right: 20px; width: 200px;">
                <el-tooltip class="item" effect="dark" :content="'活动主题：' + `${form.activityTheme || '暂无填写'}`"
                  placement="top">
                  <p class="ellipsis">活动主题：{{ form.activityTheme || '暂无填写' }}</p>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" :content="'活动概况：' + `${form.activityProfile || '暂无填写'}`"
                  placement="top">
                  <p class="ellipsis">活动概况：{{ form.activityProfile || '暂无填写' }}</p>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" :content="'服务学生人次：' + `${form.stuNumber || '暂无填写'}`"
                  placement="top">
                  <p class="ellipsis">服务学生人次：{{ form.stuNumber || '暂无填写' }}</p>
                </el-tooltip>
              </div>
              <div style="margin-right: 20px; width: 200px;">
                <el-tooltip class="item" effect="dark" :content="'活动时间：' + `${form.constructTime || '暂无填写'}`"
                  placement="top">
                  <p class="ellipsis">活动时间：{{ form.constructTime || '暂无填写' }}</p>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" :content="'活动地点：' + `${form.place || '暂无填写'}`" placement="top">
                  <p class="ellipsis">活动地点：{{ form.place || '暂无填写' }}</p>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" :content="'活动发起人：' + `${form.eventPromoter || '暂无填写'}`"
                  placement="top">
                  <p class="ellipsis">活动发起人：{{ form.eventPromoter || '暂无填写' }}</p>
                </el-tooltip>
              </div>
              <div style="width: 200px;">
                <el-tooltip class="item" effect="dark" :content="'主要参加人员名单：' + `${form.personnelList || '暂无填写'}`"
                  placement="top">
                  <p class="ellipsis">主要参加人员名单：{{ form.personnelList || '暂无填写' }}</p>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" :content="'参与人员类型：' + `${form.personnelType || '暂无填写'}`"
                  placement="top">
                  <p class="ellipsis">参与人员类型：{{ form.personnelType || '暂无填写' }}</p>
                </el-tooltip>
              </div>
            </div>
            <!-- <p>{{ handlePhoto(form.activityPhoto) }}</p> -->
            <div v-if="form.activityPhoto != null">
              <div style="margin-bottom: 20px;">活动照片</div>
              <div style="display: flex; justify-content: flex-start; flex-wrap: wrap;">
                <div v-for="item in handlePhoto(form.activityPhoto)" :key="item"
                  style="margin-right: 10px;margin-bottom: 8px;">
                  <el-image :src="imgUrl + item" alt="活动图片" style="width: 200px;"
                    :preview-src-list="[imgUrl + item]"></el-image>
                </div>
              </div>
            </div>
            <div v-else style="text-align: center;">
              暂无图片
            </div>
          </div>
        </div>
      </div>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" v-else>
        <el-form-item label="活动主题" prop="activityTheme">
          <el-input v-model="form.activityTheme" placeholder="请输入活动主题" />
        </el-form-item>
        <el-form-item label="活动概况" prop="activityProfile">
          <el-input v-model="form.activityProfile" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="参与人员类型" prop="personnelType">
          <!-- <el-input v-model="form.personnelType" placeholder="请输入参与人员类型" /> -->
          <el-select v-model="form.personnelType" placeholder="请选择参与人员类型" style="width: 100%;">
            <el-option v-for="item in personnelTypeList" :key="item.value" :label="item.value"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="主要参加人员名单" prop="personnelList">
          <el-input v-model="form.personnelList" type="textarea" rows="5" placeholder="请输入主要参加人员名单" />
        </el-form-item>
        <el-form-item label="时间" prop="constructTime">
          <el-date-picker clearable v-model="form.constructTime" type="date" value-format="yyyy-MM-dd"
            style="width: 100%;" placeholder="请选择时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="地点" prop="place">
          <el-input v-model="form.place" placeholder="请输入地点" />
        </el-form-item>
        <el-form-item label="服务学生人次" prop="stuNumber">
          <!-- <el-input v-model="form.stuNumber" placeholder="请输入服务学生人次" /> -->
          <el-input-number v-model="form.stuNumber" :min="1" :max="200" label="请输入服务学生人次"
            style="width: 100%;"></el-input-number>
        </el-form-item>
        <el-form-item label="活动照片" prop="activityPhoto">
          <image-upload v-model="form.activityPhoto" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="title === '审核' || title === '添加一站式社区模块：社区建设' || title === '修改'">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOneStopCommunityConstruction, getOneStopCommunityConstruction, delOneStopCommunityConstruction, addOneStopCommunityConstruction, updateOneStopCommunityConstruction } from "@/api/staff/oneStopCommunityConstruction";
import { getUserProfile } from "@/api/system/user"; // 获取当前用户接口
export default {
  name: "OneStopCommunityConstruction",
  data() {
    return {
      imgUrl: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 一站式社区模块：社区建设表格数据
      oneStopCommunityConstructionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        activityTheme: null,
        activityProfile: null,
        personnelType: null,
        personnelList: null,
        constructTime: null,
        place: null,
        stuNumber: null,
        activityPhoto: null,
        auditStatus: null,
        eventPromoter: null,
        startTime: null,
        endTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        activityTheme: [
          { required: true, message: "活动主题不能为空", trigger: "blur" }
        ],
        activityProfile: [
          { required: true, message: "活动概况不能为空", trigger: "blur" }
        ],
        personnelType: [
          { required: true, message: "参与人员类型不能为空", trigger: "change" }
        ],
        personnelList: [
          { required: true, message: "主要参加人员名单不能为空", trigger: "blur" }
        ],
        constructTime: [
          { required: true, message: "时间不能为空", trigger: "blur" }
        ],
        place: [
          { required: true, message: "地点不能为空", trigger: "blur" }
        ],
        stuNumber: [
          { required: true, message: "服务学生人次不能为空", trigger: "blur" }
        ],
      },
      showRole: 4,
      roleGroup: '',
      personnelTypeList: [
        { value: '学校领导' },
        { value: '部门/学校领导' },
        { value: '辅导员' },
        { value: '专任教师' },
        { value: '行政人员' },
        { value: '其他' },
      ],
      // dateRange 用于绑定 el-date-picker 组件，存储选择的日期范围
      dateRange: []
    };
  },
  created() {
    let temp = this.$store.getters.roles;
    temp.map(x => {
      if (x == "admin") {
        this.showRole = 1;
        return
      }

      if (x == "test") { //学工
        this.showRole = 1;
        return
      }

      if (x == "stumanger") { //学务
        this.showRole = 2;
        return
      }

      if (x == "testteacher") { //辅导员
        this.showRole = 3;
        return
      }

      if (x == "teststu") { //学生
        this.showRole = 4;
        return
      }
    });
    this.getUser();
  },
  methods: {
    // 获取当前登录信息
    getUser() {
      this.loading = true;
      getUserProfile().then((response) => {
        this.roleGroup = response.roleGroup;
        if (!response.roleGroup.includes("管理员")) {
          this.queryParams.eventPromoter = response.data.nickName;
          this.getList();
          return;
        }
        this.getList();
        this.loading = false;
        // this.getList();
      });
    },
    /** 查询一站式社区模块：社区建设列表 */
    getList() {
      this.loading = true;
      listOneStopCommunityConstruction(this.queryParams).then(response => {
        this.oneStopCommunityConstructionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        constructId: null,
        activityTheme: null,
        activityProfile: null,
        personnelType: null,
        personnelList: null,
        constructTime: null,
        place: null,
        stuNumber: null,
        activityPhoto: null,
        auditStatus: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getUser();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.queryParams.startTime = null
      this.queryParams.endTime = null
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.constructId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加一站式社区模块：社区建设";
    },
    /** 修改按钮操作 */
    handleUpdate(row, title) {
      this.reset();
      const constructId = row.constructId || this.ids
      getOneStopCommunityConstruction(constructId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = title;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 检查表单中是否有空字符串
          let hasEmptyString = Object.values(this.form).some(value => {
            return (value !== null && value !== undefined && (typeof value === 'string' ? value.trim() === '' : false));
          });

          if (hasEmptyString) {
            this.$modal.msgError("表单中存在空字符串，请填写完整");
            return;
          }
          if (this.form.constructId != null) {
            if (this.title === '修改') {
              this.form.auditStatus = 0
              this.form.editOpinion = ''
            }
            updateOneStopCommunityConstruction(this.form).then(response => {
              this.$modal.msgSuccess(this.title === '审核' ? "审核成功" : '修改成功');
              this.open = false;
              this.getUser();
            });
          } else {
            addOneStopCommunityConstruction(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getUser();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const constructIds = row.constructId || this.ids;
      this.$modal.confirm('是否确认删除一站式社区模块：社区建设编号为"' + constructIds + '"的数据项？').then(function () {
        return delOneStopCommunityConstruction(constructIds);
      }).then(() => {
        this.getUser();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      const selectedIds = this.ids; // 获取用户选中的数据ID

      // 构建请求参数
      const params = {
        ...this.queryParams,
        ids: selectedIds // 将选中的ID作为参数传递
      };

      // 调用下载函数，传入选中的ID
      this.download('staff/oneStopCommunityConstruction/export', params, `社区建设数据导出表_${new Date().getTime()}.xlsx`);
    },
    // handleDateChange 方法在日期范围变化时被调用
    handleDateChange(value) {
      // 如果用户选择了日期范围
      if (value) {
        // 更新 queryParams.startTime 为选择的开始时间
        this.queryParams.startTime = value[0];
        // 更新 queryParams.endTime 为选择的结束时间
        this.queryParams.endTime = value[1];
      }
      this.handleQuery()
    },
    // 处理图片显示问题
    handlePhoto(imagePathString) {
      if (imagePathString == null) {
        return []
      }
      // 将字符串根据逗号分割成数组
      // 去掉字符串两端的双引号
      imagePathString = imagePathString.replace(/"/g, '');

      // 使用split方法根据逗号分割字符串，创建数组
      let imagePathsArray = imagePathString.split(',');
      return imagePathsArray
    }
  }
};
</script>

<style scoped>
::v-deep .el-dialog__body {
  padding: 20px;
}

.ellipsis {
  overflow: hidden;
  /* 确保超出容器的文本被隐藏 */
  white-space: nowrap;
  /* 防止文本换行 */
  text-overflow: ellipsis;
  /* 超出部分显示省略号 */
}
</style>
